import React, { useEffect, useState } from 'react';
import axios from 'axios'
import PropTypes from 'prop-types';

// fetch('/data.json').then(res => res.json()).then(data => {
//   console.log("data: ", data)
// })

// 自定义hooks 是个函数
// 返回任意
// use开头的函数
interface IProps {
  method: string;
  url: string;
}

// url: 请求路径
// get/post:请求方式
// response:返回

function getAjaxData({ method = 'get', url }: IProps) {
  return new Promise((resolve, reject) => {
    (axios as any)[method](url).then((response: any) => {
      if (response.data) {
        setTimeout(() => {
          resolve(response.data)
        }, 3000)
      }
    })
  })
}

const useData = async (props: IProps) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState();

  // setLoading(true);
  // let list: any = await getAjaxData(props)
  // if (list.length) {
  //   setLoading(false)
  //   setData(list)
  // }

  useEffect(() => {

    setLoading(true);
    getAjaxData(props)
      .then((res: any) => {
        setLoading(false)
        setData(res)
      })
  }, [])

  return [data, loading]
  // return [data, loading]
}
// useData.propTypes = {
//   name: PropTypes.string
// };
useData.defaultProps = {
  method: 'get'
};

export default useData;
